 // pages/tab-cart/shop-cart.js
 const numeral = require("../../vendor/numeral/numeral.min")
 const app = getApp()
 Page({

     data: {
         startX: 0, //开始坐标
         startY: 0,
         list: [],
         cartNum: 0,
         disableList: [],
         commiunityList: [],
         supermarketList: [],
         is_separate: true,
     },

     onLoad: function() {
         wx.showLoading({
             title: '加载中...',
         })
     },
     onShow() {
         let cid = wx.getStorageSync('cid')
         this.setData({
             cid: cid,
         });
         this.loadCart()
     },
     loadCart() {
         let {
             cartNum = 0, totalPrice = 0,
         } = this.data
         app.http.get('shopping-cart/list', {
             data: {
                 cid: this.data.cid,
             }
         }).then(res => {
             let commiunityList = [],
                 list = [],
                 disableList = [],
                 supermarketList = []
             res.data.forEach(o => {
                 let startime = Date.parse(new Date()) / 1000;
                 o.isTouchMove = false
                 o.checked = true
                 if (o.goods.is_sell != 0 && o.goods.state == 1) {
                     o.pre_status = this.time_range(o.goods.group_time.group_start_time, o.goods.group_time.group_end_time)
                     list.push(o)
                 } else {
                     disableList.push(o)
                 }
                 return o
             })
             list.sort((a, b) => {
                 return a.type - b.type
             })
             let first_index = this.find_first_index(list, 'type')
             this.setData({
                 list,
                 first_index: first_index,
                 disableList,
                 checkAll: true,
             })
             if (this.data.first_index == -1 || this.data.first_index == 0) {
                 this.setData({
                     is_separate: true
                 })
             }
             this.calculateTotal()
             wx.stopPullDownRefresh()
             wx.hideLoading()
         })
     },
     find_first_index(array, attr) {
         return array.findIndex(o => o[attr] == 3) //
     },
     time_range(beginTime, endTime) {
         let this_date = new Date();
         let today = this_date.getFullYear() + "/" + (this_date.getMonth() + 1) + "/" + this_date.getDate();
         let begin_time = new Date(today + " " + beginTime);
         let end_time = new Date(today + " " + endTime);
         if (begin_time.getTime() >= end_time.getTime()) {
             end_time.setDate(this_date.getDate() + 1)
         }
         if (this_date.getTime() >= begin_time.getTime() && this_date.getTime() <= end_time.getTime()) { //距离结束
             return true
         } else { //当前时间大于 距离开始  begintime+1
             return false;
         }
     },
     /**
      * 计算商品总数
      */
     calculateTotal: function() {
         let list = this.data.list
         let selectedList = []
         let commiunityList = []
         let supermarketList = []
         let commiunityCount = 0
         let commiunityPrice = 0
         let supermarketCount = 0
         let supermarketPrice = 0
         let totalCount = 0
         let totalPrice = 0
         let cartNum = 0

         if (!list) {
             return
         }
         for (let i = 0; i < list.length; i++) {
             var good = list[i];
             cartNum += parseInt(good.quantity);
             if (good.checked && good.pre_status) { //已选择
                 selectedList.push(good)
                 totalCount += parseInt(good.quantity);
                 totalPrice += parseInt(good.quantity) * (good.goods.mall_price - 0);
                 if (good.type == 1) { //社区商品
                     commiunityList.push(good)
                     commiunityCount += parseInt(good.quantity);
                     commiunityPrice += parseInt(good.quantity) * (good.goods.mall_price - 0);
                 }
                 if (good.type == 3) { //超市商品
                     supermarketList.push(good)
                     supermarketCount += parseInt(good.quantity);
                     supermarketPrice += parseInt(good.quantity) * (good.goods.mall_price - 0);
                 }
             }
         }
         totalPrice = numeral(totalPrice).format("0,0.00")
         commiunityPrice = numeral(commiunityPrice).format("0,0.00")
         supermarketPrice = numeral(supermarketPrice).format("0,0.00")
         this.setData({
             totalCount,
             totalPrice,
             cartNum,
             selectedList,
             commiunityList,
             supermarketList,
             commiunityCount,
             commiunityPrice,
             supermarketCount,
             supermarketPrice,
         })
         this.setTabCartNum()
     },
     setTabCartNum() {
         let {
             disableList = [], cartNum = 0
         } = this.data
         disableList.map(o => {
             cartNum += parseInt(o.quantity);
         })
         app.setTabCart(cartNum)
     },
     /**
      * 修改数量
      */
     numClick(evt) {
         let dset = evt.currentTarget.dataset;
         let {
             index,
             step
         } = dset
         let list = this.data.list
         let cartid = list[index].id
         let quantity = parseInt(list[index].quantity)
         if (this.data.updating) return

         quantity = quantity + parseInt(step)

         if (quantity < 1) {
             wx.showToast({
                 icon: 'none',
                 title: '宝贝不能再减少啦~',
             })
             return
         }
         if (quantity > list[index].goods.stock && list[index].goods.stock != -1) {
             wx.showToast({
                 icon: 'none',
                 title: '库存不足啦~',
             })
             return
         }
         if (quantity > list[index].goods.max_buy_num && list[index].goods.max_buy_num != 0) {
             wx.showToast({
                 icon: 'none',
                 title: '宝贝已到达最大购买数~',
             })
             return
         }
         this.setData({
             updating: true,
             [`list[${index}].quantity`]: quantity,
         })
         this.calculateTotal()
         this.updateCartNum(cartid, step, index)
     },
     /**
      * 修改购物车数量
      */
     updateCartNum(cartid, step, index) {
         if (!cartid) return
         app.http.post('shopping-cart/update-num', {
             data: {
                 community_id: this.data.cid,
                 cart_id: cartid,
                 update_type: step == 1 ? 1 : 2,
                 type: this.data.list[index].type
             }
         }).then(res => {
             if (res.data.status == 1) {
                 this.setData({
                     [`list[${index}].quantity`]: res.data.quantity,
                 })
             } else {
                 wx.showModal({
                     title: '提示',
                     content: res.data.msg,
                     showCancel: false
                 })
             }
             this.setData({
                 updating: false,
             })
         }).catch(err => {
             this.setData({
                 updating: false,
             })
         })
     },
     /**
      * 多项选择
      */
     checkboxChange: function(e) {
         var list = this.data.list,
             values = e.detail.value,
             checkAll = !this.data.checkAll,
             k = 0

         for (var i = 0; i < list.length; ++i) {
             list[i].checked = false;
             for (var j = 0; j < values.length; ++j) {
                 if (list[i].id == values[j]) {
                     list[i].checked = true;
                     k++
                     break;
                 }
             }
             checkAll = k == list.length
         }
         this.setData({
             list,
             checkAll,
         });
         this.calculateTotal()
     },

     /**
      * 全选
      */
     selectalltap: function(e) {
         let checkAll = this.data.checkAll;
         checkAll = !checkAll
         let list = this.data.list

         for (let i = 0; i < list.length; i++) {
             list[i].checked = checkAll
         }

         this.setData({
             list,
             checkAll
         })
         this.calculateTotal();
     },

     onPullDownRefresh: function() {
         this.loadCart()
     },

     //手指触摸动作开始 记录起点X坐标
     touchstart: function(e) {
         this.setData({
             startX: e.changedTouches[0].clientX,
             startY: e.changedTouches[0].clientY,
         })
     },
     //滑动事件处理
     touchmove: function(e) {
         var index = e.currentTarget.dataset.index,
             ltype = e.currentTarget.dataset.type,
             startX = this.data.startX, //开始X坐标
             startY = this.data.startY, //开始Y坐标
             touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
             touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
             arr = ltype == 1 ? this.data.list : this.data.disableList,
             //获取滑动角度
             angle = this.angle({
                 X: startX,
                 Y: startY
             }, {
                 X: touchMoveX,
                 Y: touchMoveY
             });
         arr.forEach((v, i) => {
             v.isTouchMove = false
             //滑动超过30度角 return
             if (Math.abs(angle) > 30) return;
             if (i == index) {
                 if (touchMoveX > startX) //右滑
                     v.isTouchMove = false
                 else //左滑
                     v.isTouchMove = true
             }
         })
         //更新数据
         if (ltype == 1) {
             this.setData({
                 list: arr
             })
         } else {
             this.setData({
                 disableList: arr
             })
         }
     },
     /**
      * 计算滑动角度
      * @param {Object} start 起点坐标
      * @param {Object} end 终点坐标
      */
     angle: function(start, end) {
         var _X = end.X - start.X,
             _Y = end.Y - start.Y
         //返回角度 /Math.atan()返回数字的反正切值
         return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
     },
     del: function(e) {
         let index = e.currentTarget.dataset.index
         let ltype = e.currentTarget.dataset.type
         let arr = ltype == 1 ? this.data.list : this.data.disableList
         app.http.post('shopping-cart/delete-shopping-cart', {
             data: {
                 cart_id_group: arr[index].id,
             }
         }).then(res => {
             if (res.data.status == 1) {
                 arr.splice(index, 1)
             }
             let first_index = this.find_first_index(arr, 'type')
             if (ltype == 1) {
                 this.setData({
                     list: arr,
                     first_index: first_index,
                 })
             } else {
                 this.setData({
                     disableList: arr
                 })
             }
             this.calculateTotal()
         })

     },
     checkSeparate() {
         this.setData({
             is_separate: !this.data.is_separate
         })
     },
     submit() {
         let {
             list = [], selectedList = [], commiunityList = [], supermarketList = [], is_separate = false
         } = this.data

         function attrOnly(array, attr) { //判断是否为同一类型商品
             let first;
             if (array.length > 0) {
                 first = array[0][attr]
                 return array.every(function(item) {
                     return item[attr] == first
                 })
             }
             return true
         }

         is_separate = attrOnly(selectedList, 'type')
         if (!is_separate) {
             this.setData({
                 is_separate,
             })
             return
         }
         this.toSettlement({
             currentTarget: {
                 dataset: {
                     list: 3 //
                 }
             }
         })
     },
     toSettlement(evt) {
         let {
             selectedList = [], commiunityList = [], supermarketList = []
         } = this.data
         let list_type = evt.currentTarget.dataset.list
         let list = list_type == 1 ? commiunityList : list_type == 2 ? supermarketList : selectedList
         let arr = []

         function f(obj, keys) { //筛选属性
             return keys.reduce((result, key) => {
                 if (obj.hasOwnProperty(key)) {
                     result[key] = obj[key];
                 }
                 return result;
             }, {});
         }
         list.map(o => {
             arr.push(f(o, ['goods_id', 'sku_id', 'quantity', 'id']))
             return o
         })

         if (arr.length == 0) return
         app.okParam = {
             type: list[0].type,
             goods_info: JSON.stringify(arr),
         }
         wx.navigateTo({
             url: '/pages/order/order-ok?goods_type=' + list[0].type,
         })
     }

 })